package service

import (
	"gorm.io/gorm"
	"weekly-exam/config"
	"weekly-exam/internal/model/dao"
)

func UserList(userName string, page, pageSize int) (userList []*dao.User, err error) {
	var list []*dao.User
	err = config.DB.Where("user_name like ?", "%"+userName+"%").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return list, err
}
func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
func CreateMessage(userId, friendId int, content string) {
	message := dao.Message{
		UserId:   userId,
		FriendId: friendId,
		Content:  content,
	}
	config.DB.Create(&message)
}
